package com.duguo.dynamicmvc.view.resource;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.core.io.Resource;

import com.duguo.dynamicmvc.model.Model;
import com.duguo.dynamicmvc.view.AbstractView;
import com.duguo.dynamicmvc.view.StaticView;

public class ResourceView extends AbstractView implements StaticView {

	public static int bufferSize = 2 * 8192;

	private Resource _resource;

	public ResourceView(Resource resource) {
		_resource = resource;
	}
	
	public String getViewName() {
		return _resource.getFilename();
	}



	public void render(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
		writeResource(response, _resource);
	}

	private void writeResource(HttpServletResponse response, Resource resource) throws IOException {
		OutputStream out = response.getOutputStream();
		InputStream in = resource.getInputStream();
		try {
			writeStream(out, in);
		} finally {
			try {
				out.close();
			} catch (Exception ignore) {
			}
			try {
				in.close();
			} catch (Exception ignore) {
			}
		}

	}

	private void writeStream(OutputStream out, InputStream in) throws IOException {

		byte buffer[] = new byte[bufferSize];
		int len = bufferSize;

		while (true) {
			len = in.read(buffer, 0, bufferSize);
			if (len < 0)
				break;
			out.write(buffer, 0, len);
		}
	}
}
